package com.sunwayworld.basemodule.samplemanage.samplehandle.io;

import com.google.zxing.BarcodeFormat;
import com.sunwayworld.basemodule.basedata.exporttemplate.service.LimsGenericTemplateService;
import com.sunwayworld.basemodule.samplemanage.sample.bean.LimsSampleBean;
import com.sunwayworld.basemodule.samplemanage.sample.service.LimsSampleService;
import com.sunwayworld.basemodule.samplemanage.samplehandle.bean.LimsSampleHandleBean;
import com.sunwayworld.basemodule.samplemanage.samplehandle.service.LimsSampleHandleService;
import com.sunwayworld.cloud.lims.reporttemplate.support.util.QRPicUtil;
import com.sunwayworld.framework.io.excel.utils.ExcelUtils;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.BeanUtils;
import com.sunwayworld.framework.utils.DateTimeUtils;
import com.sunwayworld.framework.utils.ObjectUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;

// 入库单导出模板
@Component(value = "LimsSampleEnterExportTemplate")
@GikamBean
public class LimsSampleEnterExportTemplate implements LimsGenericTemplateService<String> {

    @Autowired
    private LimsSampleHandleService sampleHandleService;

    @Autowired
    private LimsSampleService sampleService;

    @Override
    public void initTemplateData(Path path, String id) {
        if (ObjectUtils.isEmpty(id)) {
            return;
        }
        LimsSampleHandleBean handleBean = sampleHandleService.selectFirstByFilter(SearchFilter.instance()
                .match("id", id).filter(MatchPattern.EQ));
        if (handleBean == null) {
            return;
        }
        MapperParameter parameter = new MapperParameter();
        parameter.setFilter(SearchFilter.instance().match("sampleHandleId", id).filter(MatchPattern.EQ));
        List<LimsSampleBean> sampleBeans = sampleService.selectSampleHandlesList(parameter);
        try {
            InputStream in = new FileInputStream(path.toString());
            Workbook workBook = WorkbookFactory.create(in);
            Sheet sheet = workBook.getSheetAt(0);
            if (!sampleBeans.isEmpty()) {
                //补充数据
                addInfo(sheet, workBook, handleBean, sampleBeans);
            }
            in.close();
            FileOutputStream outputStream = new FileOutputStream(path.toString());
            workBook.write(outputStream);
            outputStream.close();
            workBook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addInfo(Sheet sheet, Workbook wb, LimsSampleHandleBean handleBean, List<LimsSampleBean> sampleBeans) throws Exception {
        CellStyle leftCellStyle = ExcelUtils.getLeftCellStyle(wb);
        leftCellStyle.setBorderBottom(BorderStyle.THIN);
        Row row;
        // 第一行的二维码
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        QRPicUtil.generateQRCodeImage(BarcodeFormat.QR_CODE, handleBean.getHandleCode(), 180, 60, 1, byteOut);
        Drawing<?> patriarch = sheet.createDrawingPatriarch();
        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255, 6, 0, 7, 1);
        patriarch.createPicture(anchor, wb.addPicture(byteOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG));

        // 第3行 申请日期 单号
        setCellValue(sheet.getRow(2).getCell(2), DateTimeUtils.formatLocalDateTime(handleBean.getCreatedTime()), leftCellStyle);
        setCellValue(sheet.getRow(2).getCell(5), handleBean.getHandleCode(), leftCellStyle);
        // 第4行6格申请人
        setCellValue(sheet.getRow(3).getCell(5), handleBean.getCreatedByName(), leftCellStyle);

        // 第6行样本数量
        setCellValue(sheet.getRow(5).getCell(2), "" + sampleBeans.size(), leftCellStyle);

        int startRow = 8; //样本信息开始行
        //列信息：
        String[] columnNames = {"sampleCode", "sampleType", "batchcode", "locationdesc2", "locations", "-",};
        for (int i = 0; i < sampleBeans.size(); i++) {
            LimsSampleBean sampleBean = sampleBeans.get(i);
            row = sheet.createRow(i + startRow);
            setCellValue(row.createCell(0), String.valueOf(i + 1), leftCellStyle);
            for (int j = 1; j <= columnNames.length; j++) {
                String columnName = columnNames[j - 1];
                String value = ObjectUtils.toString(BeanUtils.getPropertyValue(sampleBean, columnName));

                setCellValue(row.createCell(j), value, leftCellStyle);
            }
        }
    }

    private void setCellValue(Cell cell, String value, CellStyle cellStyle) {
        cell.setCellValue(value);
        cell.setCellStyle(cellStyle);
    }
}
